<template>
  <div class="search-bar">
    <el-form :inline="true" :model="form">
      <el-form-item>
        <el-input
          v-model="form.keyword"
          placeholder="请输入关键词"
          clearable
          @keyup.enter="handleSearch"
        >
          <template #append>
            <el-button :icon="Search" @click="handleSearch" />
          </template>
        </el-input>
      </el-form-item>
      <el-form-item>
        <el-select
          v-model="form.category"
          placeholder="选择分类"
          clearable
          @change="handleSearch"
        >
          <el-option
            v-for="category in categories"
            :key="category"
            :label="category"
            :value="category"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-select
          v-model="form.tags"
          placeholder="选择标签"
          multiple
          collapse-tags
          clearable
          @change="handleSearch"
          style="width: 240px"
        >
          <el-option
            v-for="tag in tags"
            :key="tag"
            :label="tag"
            :value="tag"
          />
        </el-select>
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, computed } from 'vue'
import { Search } from '@element-plus/icons-vue'
import { useArticleStore } from '@/stores/article'
import { handleError } from '@/utils/error-handler'

const emit = defineEmits<{
  (e: 'search', params: { keyword: string; category: string; tags: string[] }): void
}>()

const store = useArticleStore()
const form = ref({
  keyword: '',
  category: '',
  tags: [] as string[]
})

// 使用计算属性获取分类和标签
const categories = computed(() => store.categories)
const tags = computed(() => store.tags)

async function loadFilters() {
  try {
    await Promise.all([
      store.fetchCategories(),
      store.fetchTags()
    ])
  } catch (error) {
    handleError(error)
  }
}

function handleSearch() {
  emit('search', {
    keyword: form.value.keyword,
    category: form.value.category,
    tags: form.value.tags
  })
}

onMounted(() => {
  loadFilters()
})
</script>

<style scoped lang="scss">
.search-bar {
  margin-bottom: 20px;
  
  :deep(.el-input) {
    width: 300px;
  }
  
  :deep(.el-select) {
    &:not(.el-select--multiple) {
      width: 200px;
    }
  }
  
  .el-form-item {
    margin-right: 16px;
    
    &:last-child {
      margin-right: 0;
    }
  }
}
</style>